<template>
	<page-meta :root-font-size="fontSizeStore.currentFontSizeRpx"></page-meta>
	<HeadNav :title="pageTitle" />
	<view class="online-supermarket">
		<view class="supermarket-layout">

			<!-- 左侧菜单 -->
			<scroll-view class="category-menu" scroll-y :scroll-into-view="leftScrollInto" scroll-with-animation>
				<view v-for="(category, index) in categories" :key="index" :id="`left-item-${index}`"
					class="category-menu__item" :class="{ 'category-menu__item--active': activeIndex === index }"
					@click="handleCategoryMenuClick(index)">
					<text class="cat_name">{{ category.name }}</text>
				</view>
			</scroll-view>

			<!-- 右侧内容 -->
			<view class="content-panel" @touchmove.stop>
				<view class="sort_view">
					<wd-sort-button :line="true" custom-class="sort_size" title="价格" v-model="priceSortValue"
						@change="priceSorthandleChange" />
					<wd-search placeholder-left hide-cancel />
				</view>


				<!-- 商品列表（修复滚动事件触发问题） -->
				<scroll-view ref="rightScrollRef" id="rightScrollView" class="content-goods__scroll" scroll-y="true"
					:scroll-into-view="targetId" scroll-with-animation @scroll="handleRightScroll">
					<view class="content-goods__container">
						<!-- 关键：确保分类标题ID与计算位置的选择器完全匹配 -->
						<view class="category-card" v-for="(category, index) in filteredCategories" :key="index"
							:id="`right-category-${index}`">
							<view class="category-card__title text12" :id="`category-title-${index}`">
								{{ category.name }}
								<span class="category-count text12">({{ category.filteredFoods.length }})</span>
							</view>

							<view v-if="category.filteredFoods.length === 0" class="no-results">
								没有找到符合条件的商品
							</view>

							<view v-for="food in category.filteredFoods" :key="food.id" class="goods-item">
								<view class="goods-item__img">
									<image :src="food.imageUrl || '/src/static/default-goods.png'" :alt="food.name">
									</image>
								</view>
								<view class="goods-item__info">
									<view>
										<text class="goods-item__name text11">{{ food.name }}</text>
										<view v-if="food.isRecommend" class="recommend-badge">推荐</view>
									</view>
									<view class="goods-item__sales text11">销量: {{ food.sales }}份</view>
									<view>
										<text class="goods-item__price text11">￥{{ food.price }}</text>
									</view>
								</view>

								<view class="goods-item__count">
									<view v-if="food.count > 0" class="count-btn count-btn--minus text11"
										@click="handleGoodsCountChange(food, -1)">-</view>
									<text v-if="food.count > 0" class="count-btn__num text11">{{ food.count }}</text>
									<view class="count-btn count-btn--plus text11"
										@click="handleGoodsCountChange(food, 1)">+
									</view>
								</view>
							</view>
						</view>
						<view class="content-goods__spacer"></view>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 底部导航 -->
		<view class="bottom-nav" v-if="!showBottomModel && !isFilterPopupOpen">
			<view class="bottom-nav__cart" @click="handleShowPaymentPopup">
				<view class="cart__wrap">
					<wd-icon name="cart" size="22px"></wd-icon>
					<view v-if="cartCount > 0" class="cart__badge" :class="{ 'cart__badge--dot': cartCount === 0 }">
						{{ cartCount > 99 ? '99+' : cartCount }}
					</view>
				</view>
				<view class="cart__text">购物车</view>
			</view>
			<view class="bottom-nav__price">
				<view class="price__content">
					<text class="price__symbol">¥</text>
					<text class="price__amount">{{ totalAmount }}</text>
				</view>
				<view class="price__desc">配送费</view>
			</view>
			<view class="bottom-nav__reserve">
				<wd-button type="error" size="medium" class="reserve__btn" :disabled="cartCount === 0">
					立即预约
				</wd-button>
			</view>
		</view>

		<!-- 支付弹窗 -->
		<view class="payment-popup">
			<wd-action-sheet title="我的购物车" v-model="showBottomModel" @close="handleHidePaymentPopup">
				<view class="cart_view">


				</view>
			</wd-action-sheet>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import {
	ref,
	nextTick,
	computed
} from 'vue'
import HeadNav from '@/components/HeadNav/index.vue'
import {
	useFontSizeStore
} from '@/stores/fontSizeStore';
import {
	jifen_chaoshiApi,
	yaodian_chaoshiApi,
	yiyuan_yuyueApi,
	bangding_shebeiApi,
	yiri_cansanApi,
	shenghuo_leiApi,
} from "@/api/products"


const fontSizeStore = useFontSizeStore();

// 当前激活的Tab
const paramName = ref("")
const pageTitle = ref("")
const priceSortValue = ref(0)

const showBottomModel = ref(false);

// 滚动相关（核心修复：确保变量初始化正确）
const rightScrollRef = ref(null)
const contentPositions = ref([]) // 存储分类标题位置，滚动联动依赖此数据
const activeIndex = ref(0)
const leftScrollInto = ref('')
const targetId = ref('')

// 筛选核心状态
const isFilterPopupOpen = ref(false)


// 商品数据
const categories = ref([])

// 计算筛选后的分类和商品
const filteredCategories = computed(() => {
	return categories.value.map(category => {
		let filteredFoods = [...category.foods].filter(food => {
			return true
		})

		return {
			...category,
			filteredFoods
		}
	}).filter(category => category.filteredFoods.length > 0)
})

// 购物车相关
const cartCount = ref(0)
const totalAmount = ref(0.00)

const calculateCategoryPositions = async () => {
	await nextTick()
	const list = filteredCategories.value
	if (list.length === 0) return

	// 清空旧数据
	contentPositions.value = new Array(list.length).fill(null)

	// 获取滚动容器位置（#rightScrollView）
	const scrollQuery = uni.createSelectorQuery()
	scrollQuery.select('#rightScrollView').boundingClientRect()
	scrollQuery.exec(async (res) => {
		const scrollViewRect = res[0]
		if (!scrollViewRect) return

		// 遍历每个分类，获取其标题位置
		for (let index = 0; index < list.length; index++) {
			const query = uni.createSelectorQuery()
			query.select(`#category-title-${index}`).boundingClientRect()
			query.exec((rectRes) => {
				const rect = rectRes[0]
				if (rect) {
					contentPositions.value[index] = {
						top: rect.top - scrollViewRect.top,
						bottom: rect.bottom - scrollViewRect.top,
						height: rect.height
					}
				} else {
					// 如果获取失败，延迟重试
					setTimeout(() => {
						const retryQuery = uni.createSelectorQuery()
						retryQuery.select(`#category-title-${index}`)
							.boundingClientRect()
						retryQuery.exec(retryRes => {
							const r = retryRes[0]
							if (r) {
								contentPositions.value[index] = {
									top: r.top - scrollViewRect.top,
									bottom: r.bottom - scrollViewRect
										.top,
									height: r.height
								}
							}
						})
					}, 50)
				}
			})
		}
	})
}

const handleRightScroll = (e) => {
	const scrollTop = e.detail.scrollTop

	if (contentPositions.value.length === 0) return

	// 滚动到顶部时，激活第一个
	if (scrollTop <= 10) {
		if (activeIndex.value !== 0) {
			activeIndex.value = 0
			leftScrollInto.value = 'left-item-0'
		}
		return
	}

	let matchedIndex = -1
	const len = contentPositions.value.length

	// 从后往前找，找到第一个“顶部在视口内”的分类
	for (let i = len - 1; i >= 0; i--) {
		const pos = contentPositions.value[i]
		if (!pos) continue

		const isLast = i === len - 1
		// 匹配规则：当前滚动距离 >= 分类顶部 - 30px，且 < 分类底部 - 30px（或最后一个分类）
		if (scrollTop >= pos.top - 30 && (isLast || scrollTop < pos.bottom - 30)) {
			matchedIndex = i
			break
		}
	}

	// 更新左侧菜单激活状态
	if (matchedIndex !== -1 && activeIndex.value !== matchedIndex) {
		activeIndex.value = matchedIndex
		leftScrollInto.value = `left-item-${matchedIndex}`
	}
}

// 5. 修复分类点击逻辑（确保右侧滚动到对应分类）
let clickTimer = null

const handleCategoryMenuClick = async (index) => {
	// ✅ 防抖：防止频繁点击
	if (clickTimer) clearTimeout(clickTimer)
	clickTimer = setTimeout(() => {
		clickTimer = null
	}, 300)

	if (index < 0 || index >= filteredCategories.value.length) return

	activeIndex.value = index
	leftScrollInto.value = `left-item-${index}`

	await nextTick()
	targetId.value = ''
	await nextTick()
	targetId.value = `category-title-${index}`

	// 延迟触发高亮
	setTimeout(() => {
		const query = uni.createSelectorQuery()
		query.select('#rightScrollView').boundingClientRect()
		query.exec((res) => {
			const rect = res[0]
			if (rect) {
				handleRightScroll({
					detail: {
						scrollTop: rect.scrollTop
					}
				})
			}
		})
	}, 150)
}



// 7. 页面挂载时初始化位置（确保首次加载有数据）
onLoad(async (options) => {
	const name = options.name;
	paramName.value = name;
	await nextTick()
	activeIndex.value = 0
	leftScrollInto.value = 'left-item-0'
	targetId.value = ''

	await nextTick()
	targetId.value = 'category-title-0'


	let res = {};
	/*
		jifen_chaoshiApi,
	yaodian_chaoshiApi,
	yiyuan_yuyueApi,
	bangding_shebeiApi,
	yiri_cansanApi,
	shenghuo_leiApi,
	*/

	if (name == 'jifen_chaoshi') {
		res = await jifen_chaoshiApi();
		pageTitle.value = "积分超市"
	} else if (name == 'yaodian_chaoshi') {
		res = await yaodian_chaoshiApi();
		pageTitle.value = "药店超市"
	} else if (name == 'yiyuan_yuyue') {
		res = await yiyuan_yuyueApi();
		pageTitle.value = "医院预约"
	} else if (name == 'bangding_shebei') {
		res = await bangding_shebeiApi();
		pageTitle.value = "绑定设备"
	} else if (name == 'yiri_cansan') {
		res = await yiri_cansanApi();
		pageTitle.value = "一日三餐"
	} else if (name == 'shenghuo_lei') {
		res = await shenghuo_leiApi();
		pageTitle.value = "生活类"
	}

	if (res?.code == 200) {
		res.data.forEach((i) => {
			i.foods.forEach((k) => {
				k.count = 0;
			})
		})
		categories.value = res.data;

		// 延迟计算位置
		setTimeout(() => calculateCategoryPositions(), 200)
	}

})
// 其他逻辑保持不变
const handleGoodsCountChange = (food, delta) => {
	if (food.count + delta < 0) return;
	food.count += delta

	let count = 0,
		amount = 0
	categories.value.forEach(cat => {
		cat.foods.forEach(f => {
			count += f.count
			amount += f.count * f.price
		})
	})
	cartCount.value = count
	totalAmount.value = amount
}

const handleShowPaymentPopup = () => {
	showBottomModel.value = true
}

const handleHidePaymentPopup = () => {
	showBottomModel.value = false
}

const priceSorthandleChange = ({ value }) => {
	console.log(value)
}
</script>

<style lang="less" scoped>
@import url("@/static/styles/family/onlineSupermarket/index.less");
@import url("@/static/styles/family/onlineSupermarket/tab-select.less");

.cat_name {
	white-space: nowrap;
	text-overflow: ellipsis;
	overflow: hidden;
}

.sort_view {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	padding-left: 20rpx;
}

/deep/ .wd-sort-button__left {
	font-size: 1.2rem !important;
}


/deep/ .wd-sort-button__right {
	font-size: 16px;
}
</style>